package com.mianyang.zhangsan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mianyang.zhangsan.common.util.StringUtils;
import com.mianyang.zhangsan.model.entity.SecAuthority;
import com.mianyang.zhangsan.mapper.SecAuthorityMapper;
import com.mianyang.zhangsan.model.entity.SecRoleAuthority;
import com.mianyang.zhangsan.service.ISecAuthorityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mianyang.zhangsan.service.ISecRoleAuthorityService;
import com.mianyang.zhangsan.service.ISecUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangjr
 * @since 2022-10-23
 */
@Service
public class SecAuthorityServiceImpl extends ServiceImpl<SecAuthorityMapper, SecAuthority> implements ISecAuthorityService {
    @Autowired
    private ISecRoleAuthorityService roleAuthorityService;

    @Override
    public List<SecAuthority> selectAuthByRoleId(Long roleId) {
        List<Long> authorities = roleAuthorityService.selectAuthorities(roleId);
        return listByIds(authorities);
    }

    private List<String> convert(List<SecAuthority> authorities) {
        if (authorities == null) {
            return null;
        }
        return authorities.stream()
                .map(SecAuthority::getAuthorityName)
                .collect(Collectors.toList());
    }

    @Override
    public List<SecAuthority> selectAuthorities(List<Long> roleIds) {
        List<Long> authorityIds = roleAuthorityService.selectAuthorities(roleIds);
        return listByIds(authorityIds);
    }

    @Override
    public Page<SecAuthority> selectAuthorities(String authorityName, int current, int pageSize) {
        QueryWrapper<SecAuthority> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(authorityName)) {
            wrapper.like("authority_name", authorityName);
        }
        return page(new Page<>(current, pageSize), wrapper);
    }

    @Override
    public List<SecAuthority> selectParentAuthorities() {
        QueryWrapper<SecAuthority> wrapper = new QueryWrapper<>();
        wrapper.eq("authority_parent", 0L);
        wrapper.eq("authority_type", 0L);
        return list(wrapper);
    }

    @Override
    public void updateRoleAndAuthRelation(Long roleId, List<SecRoleAuthority> roleAuthorities) {
        // 根据角色编号删除所有的全新啊
        roleAuthorityService.removeByRoleId(roleId);
        // 新增权限关系
        roleAuthorityService.saveBatch(roleAuthorities);
    }
}
